package it.ma.musicplayernew.holder;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.zhongdao.swing.R;

import java.util.Set;

/**
 * Author: Victor Wu <br/>
 * Email: victor-wu*foxmail.com <br/>
 * Time: 2016/1/29 11:04 <br/>
 * Description: TODO
 */
public class DeviceListHolder extends BaseViewHolder<Void> {

    @ViewInject(R.id.title)
    private TextView mTitle;

    @ViewInject(R.id.ll_title_new_devices)
    private View mLlTitleNew;

    @ViewInject(R.id.progressBar)
    private ProgressBar mProgressBar;

    // Debugging
    private static final String TAG = "DeviceListActivity";
    private static final boolean D = true;

    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    // Member fields
    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;

    private ListView pairedListView;
    private ListView newDevicesListView;

    private Button scanButton;
    private String noDevicesFond;
    private String noDevicesPaired;

    private onDeviceSelectListener mSelectListener;
    private BroadcastReceiver mReceiver;

    public DeviceListHolder(Context context) {
        super(context);
    }

    @Override
    protected View initView() {
        View deviceListView = View.inflate(mContext, R.layout.device_list_2, null);
        ViewUtils.inject(this, deviceListView);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        deviceListView.setLayoutParams(lp);
        setTitle(R.string.select_device);
        setup(deviceListView);

        return deviceListView;
    }

    private void setup(View mRootView) {
        noDevicesFond = mContext.getResources().getText(R.string.none_found).toString();
        noDevicesPaired = mContext.getResources().getText(R.string.none_paired).toString();

        scanButton = (Button) mRootView.findViewById(R.id.button_scan);
        scanButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mNewDevicesArrayAdapter != null) {
                    mNewDevicesArrayAdapter.clear(); //清空原有数据
                }
                doDiscovery();
                scanButton.setEnabled(false);
            }
        });

        // Initialize array adapters. One for already paired devices and
        // one for newly discovered devices
        mPairedDevicesArrayAdapter = new ArrayAdapter<>(mContext, R.layout.device_name);
        mNewDevicesArrayAdapter = new ArrayAdapter<>(mContext, R.layout.device_name);

        PairedDeviceClickListener pairedDeviceClickListener =  new PairedDeviceClickListener();

        pairedListView = (ListView) mRootView.findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(pairedDeviceClickListener);
        //pairedListView.setOnItemLongClickListener(mDeviceLongClickListener);

        newDevicesListView = (ListView) mRootView.findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(pairedDeviceClickListener);

        // Register for broadcasts when a device is discovered
        mReceiver = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mContext.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
//        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//        broadcastManager.registerReceiver(mReceiver, filter);

        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    @Override
    protected void refreshView(Void data) {
        mPairedDevicesArrayAdapter.clear();
        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        mRootView.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            mPairedDevicesArrayAdapter.add(noDevicesPaired);
        }
    }

    public void onDestroy() {
        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }
        // Unregister broadcast listeners
        this.mContext.unregisterReceiver(mReceiver);
    }

    /**
     * Start device discover with the BluetoothAdapter
     */
    private void doDiscovery() {
        if (D) Log.d(TAG, "doDiscovery()");

        // Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);
        setTitle(R.string.scanning);

        // Turn on sub-title for new devices
        mLlTitleNew.setVisibility(View.VISIBLE);

        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
    }

    private void setProgressBarIndeterminateVisibility(boolean b) {
        mProgressBar.setVisibility(b ? View.VISIBLE : View.GONE);
    }

    private void setTitle(int strId) {
        mTitle.setText(strId);
    }

    // The on-click listener for all devices in the ListViews
    class PairedDeviceClickListener implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // Cancel discovery because it's costly and we're about to connect
            mBtAdapter.cancelDiscovery();

            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) view).getText().toString();
            if (info.equals(noDevicesPaired) || info.equals(noDevicesFond)) {
                if(mSelectListener != null){
                    mSelectListener.onDeviceSelect(null);
                }
                return;
            }
            String address = info.substring(info.length() - 17);

            if(mSelectListener != null){
                Intent intent = new Intent();
                intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
                mSelectListener.onDeviceSelect(intent);
            }
        }
    }

    public void setOnDeviceSelectListener(onDeviceSelectListener mSelectListener) {
        this.mSelectListener = mSelectListener;
    }

   public interface onDeviceSelectListener{
       void onDeviceSelect(Intent data);
   }

    /*private AdapterView.OnItemLongClickListener mDeviceLongClickListener = new AdapterView.OnItemLongClickListener() {
        private String info;
        private String address;

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {
            if (parent.equals(pairedListView)) {
                info = mPairedDevicesArrayAdapter.getItem(position);
                if (info.equals(noDevicesPaired) || info.equals(noDevicesFond)) {
                    return true;
                }
                address = info.substring(info.length() - 17);
                BluetoothDevice remoteDevice = mBtAdapter.getRemoteDevice(address);
                try {
                    BluetoothPaired.removeBond(remoteDevice.getClass(), remoteDevice);
                    mPairedDevicesArrayAdapter.remove(info);
                } catch (Exception e) {
                    if (D) Log.e(TAG, "don't removeBond address:" + address);
                }
                return true;
            }
            return false;
        }
    };*/

    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished

    class ReceiveBroadCast extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_device);
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    mNewDevicesArrayAdapter.add(noDevicesFond);
                }
                scanButton.setEnabled(true);
            }
        }
    }

}
